
package com.microweb.toastmaster.dao.hibernate;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.microweb.toastmaster.model.TMRole;
import com.microweb.toastmaster.dao.TMRoleDao;
import org.hibernate.HibernateException;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;

import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;

public class TMRoleDaoHibernate extends BaseDaoHibernate implements TMRoleDao {
    private final Log log = LogFactory.getLog(TMRoleDaoHibernate.class);
    /**
     * @see com.microweb.toastmaster.dao.TMRoleDao#getTMRoles(com.microweb.toastmaster.model.TMRole)
     */
    public List getTMRoles(final TMRole tMRole) {
	log.debug("in TMRoleDaoHibernate.getTMRoles(). ");
	return getHibernateTemplate().find("from TMRole");
	
	/*
	if (tMRole == null) {
	    log.debug("tmRole is null.");
	    return getHibernateTemplate().find("from TMRole");
	} else {
	    // filter on properties set in the tMRole
	    HibernateCallback callback = new HibernateCallback() {
		public Object doInHibernate(Session session) throws HibernateException {
		    Example ex = Example.create(tMRole).ignoreCase().enableLike(MatchMode.ANYWHERE);
		    return session.createCriteria(TMRole.class).add(ex).list();
		}
	    };
	    return (List) getHibernateTemplate().execute(callback); 
	}*/
    }
    
    /**
     * @see com.microweb.toastmaster.dao.TMRoleDao#getTMRole(Long id)
     */
    public TMRole getTMRole(final Long id) {
	TMRole tMRole = (TMRole) getHibernateTemplate().get(TMRole.class, id);
	if (tMRole == null) {
	    log.warn("uh oh, tMRole with id '" + id + "' not found...");
	    throw new ObjectRetrievalFailureException(TMRole.class, id);
	}
	
	return tMRole;
    }
    
    public TMRole getTMRoleByName(final String rolename) throws Exception{
	List tmroles = getHibernateTemplate().find("from TMRole where name=?", rolename);
	if (tmroles == null || tmroles.isEmpty()) {
            throw new Exception("tmrole '" + rolename + "' not found...");
        } else {
            return (TMRole) tmroles.get(0);
        }
    }
    
    /**
     * @see com.microweb.toastmaster.dao.TMRoleDao#saveTMRole(TMRole tMRole)
     */
    public void saveTMRole(final TMRole tMRole) {
	getHibernateTemplate().saveOrUpdate(tMRole);
    }
    
    /**
     * @see com.microweb.toastmaster.dao.TMRoleDao#removeTMRole(Long id)
     */
    public void removeTMRole(final Long id) {
	getHibernateTemplate().delete(getTMRole(id));
    }
}
